package com.zzxx.exam.ui;

import com.zzxx.exam.entity.ExamInfo;
import com.zzxx.exam.entity.QuestionInfo;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;

/* 界面内容修改方法全部由管理员操控*/
public class ExamFrame extends JFrame {
    //管理员
    private FrameManager frameManager;
    //当前题目
    private QuestionInfo nowQuestionInfo;
    //考试信息
    private ExamInfo nowExamInfo;


    // 选项集合, 方便答案读取的处理
    private Option[] options = new Option[4];

    public ExamFrame() {
        init();
    }
    public ExamFrame(FrameManager frameManager){
        init();
        setFrameManager(frameManager);
    }
    private void init() {
        setTitle("指针信息在线测评");
        setSize(600, 380);
        //加个头像
        Image headImg = new ImageIcon("src/com/zzxx/exam/ui/pic/head.png").getImage();
        setIconImage(headImg);

        setContentPane(createContentPane());
        setLocationRelativeTo(null);

        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {// 正在关闭的时候
                int order = JOptionPane.showConfirmDialog(null, "退出会自动交卷，确定要退出？", "警告", JOptionPane.YES_NO_OPTION);
                if (order == JOptionPane.YES_OPTION){
                    //提交并退出考试
                    submitAll();
                }
            }
        });
    }

    private JPanel createContentPane() {
        JPanel pane = new JPanel(new BorderLayout());
        pane.setBorder(new EmptyBorder(6, 6, 6, 6));
        ImageIcon icon = new ImageIcon(getClass().getResource("pic/exam_title.png"));

        pane.add(BorderLayout.NORTH, new JLabel(icon));

        pane.add(BorderLayout.CENTER, createCenterPane());

        pane.add(BorderLayout.SOUTH, createToolsPane());

        return pane;
    }

    private JPanel createCenterPane() {
        JPanel pane = new JPanel(new BorderLayout());
        // 注意!
        examInfo = new JLabel("姓名: XXX 考试:科目一 考试时间:90分钟", JLabel.CENTER);
        pane.add(BorderLayout.NORTH, examInfo);

        pane.add(BorderLayout.CENTER, createQuestionPane());
        pane.add(BorderLayout.SOUTH, createOptionsPane());
        return pane;
    }

    private JPanel createOptionsPane() {
        JPanel pane = new JPanel();
        Option a = new Option(0, "A");
        Option b = new Option(1, "B");
        Option c = new Option(2, "C");
        Option d = new Option(3, "D");
        options[0] = a;
        options[1] = b;
        options[2] = c;
        options[3] = d;
        pane.add(a);
        pane.add(b);
        pane.add(c);
        pane.add(d);
        return pane;
    }

    private JScrollPane createQuestionPane() {
        JScrollPane pane = new JScrollPane();
        pane.setBorder(new TitledBorder("题目"));// 标题框

        // 注意!
        questionArea = new JTextArea();
//        questionArea.setText("问题\nA.\nB.");
//        questionArea.setText(frameManager.);

        questionArea.setLineWrap(true);// 允许折行显示1
        questionArea.setEditable(false);// 不能够编辑内容
        // JTextArea 必须放到 JScrollPane 的视图区域中(Viewport)
        pane.getViewport().add(questionArea);
        return pane;
    }

    private JPanel createToolsPane() {
        JPanel pane = new JPanel(new BorderLayout());
        pane.setBorder(new EmptyBorder(0, 10, 0, 10));
        // 注意!
        questionCount = new JLabel("题目:20 的 1题");

        timer = new JLabel("剩余时间:222秒");

        pane.add(BorderLayout.WEST, questionCount);
        pane.add(BorderLayout.EAST, timer);
        pane.add(BorderLayout.CENTER, createBtnPane());
        return pane;
    }

    private JPanel createBtnPane() {
        JPanel pane = new JPanel(new FlowLayout());
        prev = new JButton("上一题");
        next = new JButton("下一题");
        JButton send = new JButton("交卷");

        pane.add(prev);
        pane.add(next);
        pane.add(send);

        prev.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //上一题按钮
                getUserOptions();
                frameManager.prev();
            }
        });

        next.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //下一题按钮
                getUserOptions();
                frameManager.next();
            }
        });

        send.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //交卷按钮
                //提示交卷
                int order = JOptionPane.showConfirmDialog(null, "退出会自动交卷，确定要退出？", "警告", JOptionPane.YES_NO_OPTION);
                if (order == JOptionPane.YES_OPTION){
                    //交卷
                    submitAll();
                }
            }
        });

        return pane;
    }

    //更新当前题目的存储信息，也就是获取到用户选项,注意先全部清空，否则当用户修改答案的时候，集合内的历史答案都还在
    private void getUserOptions() {
        //获取用户选项，用JCheckBox自带的确认方法去判断
        List<Integer> userAnswers = new ArrayList<>();
        for (int i = 0; i < options.length; i++) {
            if (options[i].isSelected()){
                nowQuestionInfo.getUserAnswers().add(options[i].value);
                userAnswers.add(options[i].value);
            }
        }
        nowQuestionInfo.setUserAnswers(userAnswers);
    }

    //交卷方法
    private void submitAll() {
        getUserOptions();
        frameManager.submit();
    }

    //返回当前题目信息
    public QuestionInfo getNowQuestion() {
        getUserOptions();
        return nowQuestionInfo;
    }

    //清空选项，优化：不是清空，而是赋值，因为没写过的题用户答案为空，所以可以当做有答案的赋值
    public void refreshCheckBox() {
//        for (int i = 0; i < options.length; i++) {
//            options[i].setSelected(false);
//        }
        //优化
        for (int i = 0; i < options.length; i++){
            if (nowQuestionInfo.getUserAnswers().contains(options[i].getValue())){
                //包含，则改为已选
                options[i].setSelected(true);
            }else {
                options[i].setSelected(false);
            }
        }
    }

    //更新题号
    public void refreshQuesIndex() {
        questionCount.setText("题目: " + nowExamInfo.getQuestionCount() + " 的" + nowQuestionInfo.getQuestionIndex() + " 题");
    }

    /**
     * 使用内部类扩展了 JCheckBox 增加了val 属性, 代表答案值
     */
    class Option extends JCheckBox {
        int value;

        public Option(int val, String txt) {
            super(txt);
            this.value = val;
        }

        public int getValue() {
            return value;
        }
    }

    private JTextArea questionArea;

    private JButton next;

    private JButton prev;

    private JLabel questionCount;

    private JLabel timer;
    private JLabel examInfo;

/*    public void updateTime(long h, long m, long s) {
        String time = h + ":" + m + ":" + s;
        if (m < 5) {
            timer.setForeground(new Color(0xC85848));
        } else {
            timer.setForeground(Color.blue);
        }
        timer.setText(time);
    }*/

    //优化后的
    public void updateTime(String h, String m, String s) {
        String time = h + ":" + m + ":" + s;
        if (Integer.parseInt(m) < 5) {
            timer.setForeground(new Color(0xC85148));
        } else {
            timer.setForeground(Color.blue);
        }
        timer.setText(time);
    }

    public Option[] getOptions() {
        return options;
    }

    public JTextArea getQuestionArea() {
        return questionArea;
    }

    public void setFrameManager(FrameManager frameManager) {
        this.frameManager = frameManager;
    }

    public void setNowQuestionInfo(QuestionInfo nowQuestionInfo) {
        this.nowQuestionInfo = nowQuestionInfo;
    }

    public JLabel getExamInfo() {
        return examInfo;
    }

    public void setNowExamInfo(ExamInfo nowExamInfo) {
        this.nowExamInfo = nowExamInfo;
    }

    public ExamInfo getNowExamInfo() {
        return nowExamInfo;
    }
}